package com.sky.controller.user;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.mybatis.mp.core.mybatis.mapper.context.Pager;
import com.sky.constant.UserActionConstant;
import com.sky.context.BaseContext;
import com.sky.result.Result;
import com.sky.service.RecommendationService;
import com.sky.service.UsercollectionsService;
import com.sky.vo.UserCollectionVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户收藏相关接口
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserCollectionController {

    @Autowired
    private UsercollectionsService usercollectionsService;

    @Autowired
    private RecommendationService recommendationService;

    /**
     * 检查图书是否已收藏
     *
     * @param bookId 图书ID
     * @return "1" 表示已收藏，"0" 表示未收藏
     */
    @SaCheckLogin
    @GetMapping("/favorites/check/{bookId}")
    public Result getBookCheckIsFavorite(@PathVariable Integer bookId) {
        log.info("检查图书是否已收藏：{}", bookId);
        String result = usercollectionsService.getBookCheckIsFavorite(bookId);
        return Result.success(result);
    }

    /**
     * 添加收藏
     * @param bookId 图书ID
     * @return 操作结果
     */
    @SaCheckLogin
    @PostMapping("/favorites/add/{bookId}")
    public Result addFavorite(@PathVariable Integer bookId) {
        log.info("添加收藏：{}", bookId);
        try {
            // 1. 获取当前用户ID
            Integer userId = Math.toIntExact(BaseContext.getCurrentId());
            
            // 2. 添加收藏记录
            usercollectionsService.addFavorite(userId, bookId);
            
            // 3. 记录收藏行为（用于推荐系统）
            recommendationService.recordUserAction(userId, bookId, UserActionConstant.COLLECT);
            
            return Result.success();
        } catch (Exception e) {
            log.error("添加收藏失败", e);
            return Result.error("添加收藏失败：" + e.getMessage());
        }
    }

    /**
     * 取消收藏
     * @param bookId 图书ID
     * @return 操作结果
     */
    @SaCheckLogin
    @DeleteMapping("/favorites/cancel/{bookId}")
    public Result cancelFavorite(@PathVariable Integer bookId) {
        log.info("取消收藏：{}", bookId);
        try {
            // 1. 获取当前用户ID
            Integer userId = Math.toIntExact(BaseContext.getCurrentId());

            // 2. 取消收藏
            usercollectionsService.cancelFavorite(userId, bookId);

            return Result.success();
        } catch (Exception e) {
            log.error("取消收藏失败", e);
            return Result.error("取消收藏失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户收藏列表（分页）
     * @param page 页码
     * @param pageSize 每页数量
     * @return 分页后的收藏列表（包含图书详细信息）
     */
    @SaCheckLogin
    @GetMapping("/favorites/list")
    public Result<Pager<UserCollectionVO>> getFavoritesList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("获取用户收藏列表，页码：{}，每页数量：{}", page, pageSize);
        try {
            Integer userId = Math.toIntExact(BaseContext.getCurrentId());
            Pager<UserCollectionVO> pager = usercollectionsService.getUserCollectionsByPage(userId, page, pageSize);
            return Result.success(pager);
        } catch (Exception e) {
            log.error("获取用户收藏列表失败", e);
            return Result.error("获取收藏列表失败：" + e.getMessage());
        }
    }
} 